package mark.tom.sail;

import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import static mark.tom.sail.Util.log_i;

public class WorkManagerCollector implements RecordCollector {

    private final Context mContext;

    public WorkManagerCollector(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void doInBackground(@NonNull String generatorFileName,
                               @NonNull String convertedData,
                               @NonNull FileStorage fileStorage,
                               @NonNull LogInterceptor logInterceptor) {
        OneTimeWorkRequest compressionWork = new OneTimeWorkRequest.Builder(AnalyticsCollectWork.class)
                .setInputData(new Data.Builder()
                        .putString("generatorFileName", generatorFileName)
                        .putString("convertedData", convertedData)
                        .build())
                .addTag("Sail")
                .build();
        WorkManager.getInstance(mContext).enqueue(compressionWork);
    }

    public final static class AnalyticsCollectWork extends Worker {

        public AnalyticsCollectWork(@NonNull Context context,
                                    @NonNull WorkerParameters workerParams) {
            super(context, workerParams);
        }

        @NonNull
        @Override
        public Result doWork() {
            Result result = Result.success();
            try {
                Data data = getInputData();
                String generatorFileName = data.getString("generatorFileName");
                String convertedData = data.getString("convertedData");
                log_i(Sail.mLogInterceptor, "Job Added And FileName is " + generatorFileName + " FileContent is " + convertedData);
                if (null == generatorFileName
                        || TextUtils.isEmpty(generatorFileName)
                        || null == convertedData
                        || TextUtils.isEmpty(convertedData)
                        || !Sail.mFileStorage.saveLogContent(generatorFileName, convertedData)) {
                    throw new RuntimeException();
                }
                log_i(Sail.mLogInterceptor, "Work Run And Data Has Been Saved");
            } catch (Exception ex) {
                result = Result.failure();
            }
            return result;
        }
    }
}
